package com.letoo.sso.dataaccess.dao.cahce.impl;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Repository;

import com.letoo.sso.dataaccess.dao.cahce.CounterCacheDAO;

@Repository("counterCacheDAO")
public class CounterCacheDAOImpl extends BaseCacheDAOImpl implements CounterCacheDAO {

    public static String PREFIX_COUNTER = "SN:";

    @Override
    public long nextCount(final String field) {
        Long result = getRedisTemplate().execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) {
                byte[] key = serialize(PREFIX_COUNTER + field);
                Long res = connection.incr(key);
                return res;
            }
        });
        return result;
    }

    @Override
    public long nextCountOfLength(final String field, final int length) {
        Long result = getRedisTemplate().execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) {
                byte[] key = serialize(PREFIX_COUNTER + field);
                Long res = connection.incrBy(key, length);
                return res;
            }
        });
        return result;
    }

}
